<template lang="pug">
    span(:class="{'control-amount-working': working}") {{model.value.value | fixed}}
</template>

<script>
export default {
  name: "control-amount",
  props: {
    model: {
      type: Object,
      default() {
        return {
          value: { name: "", value: 0 },
          amount: 0,
          name: "无标题",
          unit: "U",
          max: 0,
          min: 0,
          init_val: false, // 初始值，如果为false则没有初始值
          increment: 1,
          no2MaxZero: false, // 当值等于0时，按向下按钮，不跳到最大值
          no2MinOnMax: false // 当值最大时，按向上按钮，不跳到最小值
        };
      }
    },
    working: { type: Boolean, default: false }
  },
  model: { event: "update", prop: "model" },
  methods: {
    up() {
      let value = this.model.value.value;
      const name = this.model.value.name;
      const min = this.model.min;
      const max = this.model.max;
      const no2MinOnMax = this.model.no2MinOnMax;

      if (value >= max) {
        value = no2MinOnMax ? max : min; // 是否允許当值等于最大值时，按向上按钮，值变为最小值
        this.model.value = { value, name: value };
        return;
      }

      if (value < min) {
        value = min;
        this.model.value = { value, name: value };
        return;
      }

      value = (value * 10 + this.model.increment * 10) / 10;
      this.model.value = { value, name: value };

      if (this.model.onChange) this.model.onChange(this.model);
    },

    down() {
      let value = this.model.value.value;
      const name = this.model.value.name;
      const min = this.model.min;
      const max = this.model.max;
      const no2MaxZero = this.model.no2MaxZero;

      if (value <= min) {
        value = no2MaxZero ? min : max; // 是否允許当值等于最小值时，按向下按钮，值变为最大值
        this.model.value = { value, name: value };
        return;
      }

      value = (value * 10 - this.model.increment * 10) / 10;
      this.model.value = { value, name: value };

      if (this.model.onChange) this.model.onChange(this.model);
    }
  },
  filters: {
    fixed(val) {
      val = val + "";
      if (parseInt(val) < 10) val = "0" + val;
      if (val.length > 2 && val.indexOf("0") === 0) val = val.substring(1);
      return val;
    }
  }
};
</script>
